﻿using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Entities;
using IdentityServer4.EntityFramework.Extensions;
using IdentityServer4.EntityFramework.Interfaces;
using IdentityServer4.EntityFramework.Options;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdentityServer4Blazor.Model
{
    public class IdentityServer4ApiDbContext : IdentityDbContext<User, Role, int, IdentityUserClaim<int>,
    UserRole, IdentityUserLogin<int>,
    IdentityRoleClaim<int>, IdentityUserToken<int>>
    {

        public IdentityServer4ApiDbContext(DbContextOptions<IdentityServer4ApiDbContext> options)
            : base(options)
        {
        }
        ///// <summary>
        ///// Gets or sets the <see cref="DbSet{PersistedGrant}"/>.
        ///// </summary>
        //public DbSet<PersistedGrant> PersistedGrants { get; set; }
        ///// <summary>
        ///// Gets or sets the <see cref="DbSet{DeviceFlowCodes}"/>.
        ///// </summary>
        //public DbSet<DeviceFlowCodes> DeviceFlowCodes { get; set; }

        //Task<int> IPersistedGrantDbContext.SaveChangesAsync() => base.SaveChangesAsync();
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);
            builder.Entity<UserRole>(userRole =>
            {
                userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

                userRole.HasOne(ur => ur.Role)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.RoleId)
                    .IsRequired();

                userRole.HasOne(ur => ur.User)
                    .WithMany(r => r.UserRoles)
                    .HasForeignKey(ur => ur.UserId)
                    .IsRequired();
            });
            builder.Entity<User>(user =>
            {
                user.HasMany(x => x.UserRoles).WithOne(x => x.User);
                user.HasMany(x => x.Claims).WithOne().HasForeignKey(x => x.UserId).IsRequired();
            });
            builder.Entity<Role>(role =>
            {
                role.HasMany(x => x.UserRoles).WithOne(x => x.Role);
            });
        }
    }
}
